<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\UserInfo;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use \Auth;
use \Cache;
use App\Models\User;
use Illuminate\Support\Str;
use GuzzleHttp\Client;
use EasyWeChat\Factory;
use App\Common\Tools\Emchat;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function loginBySMS(Request $request)
    {
        $this->validate($request, [
            'phone' => 'required',         //手机号码
            'code' => 'required|numeric',  //用户收到的短消息
            'open_id' => 'required|numeric',  //openid
        ]);
        $phone = $request->phone;
        $success = false;

        $whitelist = \Storage::get('jsons/iOSWhiteList.json');
        $whitePhones = json_decode($whitelist, true);
        $whitePhones = $whitePhones['phones'];
        if (in_array($phone, $whitePhones)) {
            $success = true;
        }

        if ($request->type == 'invite') {
            $userphone = User::where('phone', $phone)->first();
            if (!empty($userphone)) {
                return response()->json(['deny' => 1], 200);
            }
        }

        if ($request->code == Cache::get('login_' . $request->phone)) {
            $success = true;
        }

        if ($success) {
            $user = User::withTrashed()->where('phone', $request->phone)->first();

            if (empty($user)) {
                $user = User::create([
                    'phone' => $phone,
                    'name' => $phone,
                    'open_id' => $request->open_id,
                    'password' => bcrypt($request->open_id),  // would has default password for new user.
                ]);
            }

            $token = $user->createToken('API_Token')->accessToken;
            return response()->json(['user_id' => $user->id, 'token' => $token]);
        }

        return response('验证码错误，请重试！', 403);
    }


    //-----------------------------------------------------------------------

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function loginByOpenid(Request $request)
    {
        $this->validate($request, [
            'code' => 'required',         //open_id
            'phone' => 'nullable',         //手机号,首次传入
        ]);
        $app = Factory::miniProgram(config('wechat.mini_program.default'));
        try {
            $session = $app->auth->session($request->code);
            if (isset($session['errcode'])) {
                throw new \Exception(join(':', $session));
            }
            if ($session['openid']) {
                Cache::put('session_key_' . $session['openid'], $session['session_key'], 43200);
                $user = User::withTrashed()->where('open_id', $session['openid'])->first();
                $response['if_new'] = 0;
                //注册新用户
                if (empty($user)) {
                    if(empty($request->phone)){
                        return $this->errorReturn('首次登录请填写手机');
                    }
                    $phone_user = User::withTrashed()->where('phone', $request->phone)->first();
                    if(empty($phone_user)){
                        $user = User::create([
                            'open_id' => $session['openid'],
                            'password' => bcrypt($session['openid']),  // would has default password for new user.
                            'phone' => $request->phone,
                        ]);
                        $response['if_new'] = 1;
                    }else{
                        $phone_user->open_id = $session['openid'];
                        $phone_user->save();
                    }
                    $user = User::withTrashed()->where('open_id', $session['openid'])->first();
                }
                $token = $user->createToken('Mini Program')->accessToken;
//                $http = new Client();
//                $response = $http->post(env('APP_URL') . '/oauth/token', [
//                    'form_params' => [
//                        'grant_type' => 'password',
//                        'client_id' => env('CLIENT_ID'),
//                        'client_secret' => env('CLIENT_SECRET'),
//                        'username' => $session['openid'],
//                        'password' => $session['openid'],
//                        'scope' => '',
//                    ],
//                ]);
//                $response = json_decode((string)$response->getBody(), true);
//                $response['if_new'] = empty($user->phone)?1:0;

                $user_infos = UserInfo::where('user_id', $user->id)->first();
                if(empty($user_infos)){
                    $response['if_new'] = 1;
                }

                $response['user_id'] = $user->id;
                $response['token'] = $token;
                return $this->successReturn($response);
            }
            return $this->errorReturn('获取openid失败');

        } catch (\Throwable $e) {
            return $this->errorReturn($e->getMessage());

        }

    }


    public function loginByTtOpenid(Request $request)
    {
        $this->validate($request, [
            'code' => 'required',         //open_id
            'phone' => 'nullable',         //手机号,首次传入
        ]);
        $app = new \Qbhy\TtMicroApp\TtMicroApp([
            'access_key' => 'tt3ecd4870a1f7dbb0',
            'secret_key' => '4880224bb36e457637418715447bed6fa314b570',
            'debug' => true,
        ]);
        $session = $app->auth->session($request->code);

        $user = User::withTrashed()->where('tt_open_id', $session['openid'])->first();
        $response['if_new'] = 0;
        //注册新用户
        if (empty($user)) {
            if(empty($request->phone)){
                return $this->errorReturn('首次登录请填写手机');
            }
            $phone_user = User::withTrashed()->where('phone', $request->phone)->first();
            if(empty($phone_user)){
                User::create([
                    'tt_open_id' => $session['openid'],
                    'password' => bcrypt($session['openid']),  // would has default password for new user.
                    'phone' => $request->phone,
                ]);

                $response['if_new'] = 1;
            }else{
                $phone_user->tt_open_id = $session['openid'];
                $phone_user->save();
            }
            $user = User::withTrashed()->where('tt_open_id', $session['openid'])->first();
        }
        $token = $user->createToken('Mini Program')->accessToken;
//        $http = new Client();
//        $response = $http->post(env('APP_URL') . '/oauth/token', [
//            'form_params' => [
//                'grant_type' => 'password',
//                'client_id' => env('CLIENT_ID'),
//                'client_secret' => env('CLIENT_SECRET'),
//                'username' => $user->id,
//                'password' => $user->id,
//                'scope' => '',
//            ],
//        ]);
//        $response = json_decode((string)$response->getBody(), true);

        $user_infos = UserInfo::where('user_id', $user->id)->first();
        if(empty($user_infos)){
            $response['if_new'] = 1;
        }

        $response['user_id'] = $user->id;
        $response['token'] = $token;
        return $this->successReturn($response);


    }


}
